package com.netty.admin.aspect;

import cn.hutool.core.date.DateTime;
import com.netty.admin.service.LogService;
import com.netty.common.annotation.Log;
import com.netty.common.enums.BusinessStatus;
import com.netty.common.util.ServletUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestUtils;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 操作日志记录处理
 *
 * @author ruoyi
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private LogService logService;

    //    aop切面的实现??  在注解上加上切点，即切入带有此注解的方法
    @Pointcut("@annotation(com.netty.common.annotation.Log)")
    public void logAspect() {
    }

    /**
     *
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning("logAspect()")
    public void doAfterReturning(JoinPoint joinPoint) {

        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        Log annotation = method.getAnnotation(Log.class);

        com.netty.common.entity.Log logInfo = new com.netty.common.entity.Log();
        logInfo.setOperIp(ServletUtils.getRequest().getRemoteAddr());
        logInfo.setOperUrl(ServletUtils.getRequest().getRequestURI());
        logInfo.setOperTime(new DateTime().toString());
        logInfo.setOperStatus(BusinessStatus.SUCCESS.ordinal());
        logInfo.setBusinessType(annotation.businessType());
        logInfo.setTitle(annotation.title());
        logInfo.setOperatorType(annotation.operatorType().ordinal());
        logInfo.setRequestMethod(methodSignature.getMethod().getName());

        //异步入库
        logService.insertLog(logInfo);
    }
}
